package com.ficus.road.maintain.file;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @author xiawen yang
 * @date 2022/6/20 下午3:06
 */
@Slf4j
public abstract class AbstractFileClient<Config extends FileClientConfig> implements FileClient {

    /**
     * 配置名称
     */
    private final String clientName;

    protected Config config;

    public AbstractFileClient(String clientName, Config config) {
        this.clientName = clientName;
        this.config = config;
    }

    /**
     * int to byte[]
     *
     * @param a
     * @return
     */
    public static byte[] intToByteArray(int a) {
        return new byte[]{
                (byte) ((a >> 24) & 0xFF),
                (byte) ((a >> 16) & 0xFF),
                (byte) ((a >> 8) & 0xFF),
                (byte) (a & 0xFF)
        };
    }

    public static int byteArrayToInt(byte[] bytes) {
        return ((bytes[0] & 0xFF) << 24) |
                ((bytes[1] & 0xFF) << 16) |
                ((bytes[2] & 0xFF) << 8) |
                ((bytes[3] & 0xFF) << 0);
    }

    @Override
    public String getClientName() {
        return clientName;
    }

    /**
     * 自定义初始化
     */
    protected abstract void doInit();

    protected abstract UploadResult upload0(InputStream inputStream, String path, String contentType) throws Exception;

    public final void init() {
        doInit();
        log.info("[init][配置({}) 初始化完成]", config);
    }

    @Override
    public UploadResult upload(byte[] content, String path) throws Exception {
        InputStream inputStream = new ByteArrayInputStream(content);
        //上传文件
        // image/jpg --> png
        UploadResult uploadResult = upload0(inputStream, "image/jpg", path);
        if (uploadResult.getCode() != 200) {
            log.error("upload0 failed");
            // 如果失敗，重試一次
            uploadResult = upload0(inputStream, "image/jpg", path);
        }
        return uploadResult;
    }
}
